package com.matrix.draft.sockettest.day6.server;

import com.matrix.draft.sockettest.day6.ConfigProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyServer {

    private ConfigProperties properties = new ConfigProperties();

    public void start() {
        // 1.创建负责处理连接的BossGroup和负责读写的workerGroup
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        // 2.创建服务启动器
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            // 3.设置服务启动器
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // 服务器使用什么样的Channel
                    .option(ChannelOption.SO_BACKLOG, 128) // 线程队列等待连接的个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true) // 保持活动连接状态
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) {
                            ch.pipeline().addLast(new DefaultChannelHandler());
                        }
                    });
            // 4.绑定端口并启动
            ChannelFuture cf = bootstrap.bind(properties.getProvider().getHost(), properties.getProvider().getPort()).sync();
            System.err.println("Netty Server is running at "+properties.getProvider().getHost()+":"+properties.getProvider().getPort()+"...");
            // 5.未来关闭
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 优雅退出
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }


    public static void main(String[] args) {
        new NettyServer().start();
    }
}